import { getDoctorList } from '../api/Indfo'
import { 
  mockDoctors, 
  type Doctor, 
  filterDoctorsByDepartment, 
  searchDoctorsByName,
  sortDoctorsByRating,
  sortDoctorsByPrice,
  getPaginatedDoctors,
  getDoctorStats
} from '../data/mockDoctors'

// 医生服务类
export class DoctorService {
  private doctors: Doctor[] = []
  private isLoading: boolean = false
  private error: string | null = null
  private currentPage: number = 1
  private pageSize: number = 5
  private hasMore: boolean = true

  // 获取医生列表 - 调用真实API
  async fetchDoctors(): Promise<Doctor[]> {
    this.isLoading = true
    this.error = null

    try {
      console.log('🚀 开始调用真实API获取医生列表...')
      
      // 调用真实API获取医生列表
      const res = await getDoctorList({
        pageCode: '1',
        pageSize: '50' // 获取更多数据用于分页
      })
      
      console.log('📡 API响应:', res)
      
      // 检查API响应格式
      if (res.data && res.data.code === 20000) {
        this.doctors = Array.isArray(res.data.data) ? res.data.data : []
        console.log('✅ 从真实API获取医生数据成功:', this.doctors)
        console.log('📊 医生总数:', this.doctors.length)
        return this.doctors
      } else if (res.data && res.data.code) {
        throw new Error(`API返回错误状态码: ${res.data.code}, 消息: ${res.data.message || '未知错误'}`)
      } else {
        // 如果响应格式不标准，尝试直接使用数据
        let doctorsData = []
        if (res.data && Array.isArray(res.data.data)) {
          doctorsData = res.data.data
        } else if (Array.isArray(res.data)) {
          doctorsData = res.data
        } else if (Array.isArray(res)) {
          doctorsData = res
        }
        
        this.doctors = doctorsData
        console.log('⚠️ API响应格式不标准，尝试使用数据:', this.doctors)
        console.log('📊 医生总数:', this.doctors.length)
        return this.doctors
      }
    } catch (error) {
      console.warn('⚠️ API请求失败，使用模拟数据:', error)
      this.doctors = mockDoctors
      this.error = `API连接失败: ${error instanceof Error ? error.message : '未知错误'}，使用模拟数据`
      return this.doctors
    } finally {
      this.isLoading = false
    }
  }

  // 获取所有医生
  getAllDoctors(): Doctor[] {
    // 确保返回数组，如果doctors为空或不是数组则返回模拟数据
    if (!Array.isArray(this.doctors) || this.doctors.length === 0) {
      console.log('⚠️ doctors数组为空或不是数组，返回模拟数据')
      return mockDoctors
    }
    return this.doctors
  }

  // 按科室筛选医生 - 优先使用API筛选
  async getDoctorsByDepartment(department: string): Promise<Doctor[]> {
    try {
      // 如果科室不是"全部"，则调用API进行筛选
      if (department !== '全部') {
        console.log(`🔍 调用API筛选${department}科室医生...`)
        
        const res = await getDoctorList({
          pageCode: '1',
          pageSize: '50',
          admin: department
        })
        
        if (res.data && res.data.code === 20000) {
          const filteredDoctors = Array.isArray(res.data.data) ? res.data.data : []
          console.log(`✅ ${department}科室API筛选成功，获取到${filteredDoctors.length}名医生`)
          return filteredDoctors
        } else {
          console.warn(`⚠️ ${department}科室API筛选失败，状态码: ${res.data?.code}`)
        }
      }
      
      // 如果科室是"全部"或API调用失败，使用本地筛选
      console.log(`🔄 使用本地筛选${department}科室医生...`)
      return filterDoctorsByDepartment(this.doctors, department)
    } catch (error) {
      console.warn(`⚠️ ${department}科室筛选API调用失败，使用本地筛选:`, error)
      return filterDoctorsByDepartment(this.doctors, department)
    }
  }

  // 按姓名搜索医生
  searchDoctors(name: string): Doctor[] {
    return searchDoctorsByName(this.doctors, name)
  }

  // 按评分排序医生
  sortDoctorsByRating(order: 'asc' | 'desc' = 'desc'): Doctor[] {
    return sortDoctorsByRating(this.doctors, order)
  }

  // 按价格排序医生
  sortDoctorsByPrice(order: 'asc' | 'desc' = 'asc'): Doctor[] {
    return sortDoctorsByPrice(this.doctors, order)
  }

  // 获取分页医生列表
  getPaginatedDoctors(page: number = 1, pageSize: number = 10) {
    return getPaginatedDoctors(this.doctors, page, pageSize)
  }

  // 获取当前页的医生列表
  getCurrentPageDoctors(): Doctor[] {
    const startIndex = (this.currentPage - 1) * this.pageSize
    const endIndex = startIndex + this.pageSize
    return this.doctors.slice(startIndex, endIndex)
  }

  // 加载更多医生
  async loadMoreDoctors(): Promise<Doctor[]> {
    if (!this.hasMore || this.isLoading) {
      return []
    }

    this.isLoading = true
    this.currentPage += 1

    // 模拟网络延迟
    await new Promise(resolve => setTimeout(resolve, 500))

    const newDoctors = this.getCurrentPageDoctors()
    this.hasMore = newDoctors.length > 0

    this.isLoading = false
    return newDoctors
  }

  // 重置分页状态
  resetPagination(): void {
    this.currentPage = 1
    this.hasMore = true
  }

  // 获取分页状态
  getPaginationState() {
    return {
      currentPage: this.currentPage,
      pageSize: this.pageSize,
      hasMore: this.hasMore,
      total: this.doctors.length
    }
  }

  // 获取医生统计信息
  getStats() {
    return getDoctorStats(this.doctors)
  }

  // 获取加载状态
  getLoadingState(): boolean {
    return this.isLoading
  }

  // 获取错误信息
  getError(): string | null {
    return this.error
  }

  // 清除错误
  clearError(): void {
    this.error = null
  }

  // 重新加载数据
  async reload(): Promise<Doctor[]> {
    return this.fetchDoctors()
  }
}

// 创建单例实例
export const doctorService = new DoctorService()

// 便捷函数
export const useDoctorService = () => {
  return {
    fetchDoctors: () => doctorService.fetchDoctors(),
    getAllDoctors: () => doctorService.getAllDoctors(),
    getDoctorsByDepartment: (department: string) => doctorService.getDoctorsByDepartment(department),
    searchDoctors: (name: string) => doctorService.searchDoctors(name),
    sortDoctorsByRating: (order: 'asc' | 'desc') => doctorService.sortDoctorsByRating(order),
    sortDoctorsByPrice: (order: 'asc' | 'desc') => doctorService.sortDoctorsByPrice(order),
    getPaginatedDoctors: (page: number, pageSize: number) => doctorService.getPaginatedDoctors(page, pageSize),
    getCurrentPageDoctors: () => doctorService.getCurrentPageDoctors(),
    loadMoreDoctors: () => doctorService.loadMoreDoctors(),
    resetPagination: () => doctorService.resetPagination(),
    getPaginationState: () => doctorService.getPaginationState(),
    getStats: () => doctorService.getStats(),
    getLoadingState: () => doctorService.getLoadingState(),
    getError: () => doctorService.getError(),
    clearError: () => doctorService.clearError(),
    reload: () => doctorService.reload()
  }
}

export default doctorService
